import { registerClass } from "../../../cfw/tools/class_decorator";
import BaseAd from "../../core/base/BaseAd";
import { SDKLogicState, SDKState } from "../../SDKDefine";

/**
 * https://minigame.vivo.com.cn/documents/#/api/ad/box-ad
 * 1092
 * 盒子广告两种样式同时只能展示一种
 * 盒子广告不支持预览，直接请求即可，九宫格广告建议关闭后再次show
 */
@registerClass('VivoBoxPortalAd')
export default class VivoBoxPortalAd extends BaseAd {

    protected name: string = "VivoBoxPortalAd"

    open() {
        this.setLogicState(SDKLogicState.open)
        this.create();
        this.show()
    }

    // protected onLoadLogic(): void {
    //     if (this.isLogicState(SDKLogicState.open)) {
    //         this.show()
    //     }
    // }

    create() {
        this.destroy();
        this.setState(SDKState.loading)
        if (this.sdk.createBoxPortalAd) {
            let data = {
                posId: this.adUnitID,
                image: this.param.image,
                marginTop: this.param.marginTop,
            }
            this.ad = this.sdk.createBoxPortalAd(data)
            this.ad.onError(this.getFunc(this.onError))
            this.ad.onShow(this.getFunc(this.onShow))
            this.ad.onLoad(this.getFunc(this.onLoad))
            this.ad.onClose(this.getFunc(this.onClose))
            // 广告数据加载成功后展示
            console.log(' 广告数据加载成功后展示', data)
        } else {
            console.log('暂不支持互推盒子相关 API')
        }
    }


    onShow() {

    }

    onClose() {
        console.log('close this.boxPortalAd.isDestroyed ', this.ad.isDestroyed)
        if (this.ad.isDestroyed) {
            return
        }
        // 当九宫格关闭之后，再次展示Icon
        this.show()
    }

    show() {
        this.setLogicState(SDKLogicState.close)
        this.setState(SDKState.show)
        if (this.ad) {
            this.ad.show().then(function () {
                console.log('show success')
            }).catch(function (error) {
                console.log('show fail with:' + error.errCode + ',' + error.errMsg)
            })
        }
    }

    close() {
        this.setState(SDKState.close)
        if (this.ad) {
            this.ad.hide().then(function () {
                console.log('hide success')
            }).catch(function (error) {
                console.log('hide fail with:' + error.errCode + ',' + error.errMsg)
            })
        }
    }


    destroy() {
        this.setState(SDKState.destroy)
        if (this.ad) {
            this.ad.isDestroyed = true
            this.ad.offError(this.getFunc(this.onError))
            this.ad.offShow(this.getFunc(this.onShow))
            this.ad.offLoad(this.getFunc(this.onLoad))
            this.ad.offClose(this.getFunc(this.onClose))
            this.ad.destroy().then(function () {
                console.log('destroy success')
            }).catch(function (error) {
                console.log('destroy fail with:' + error.errCode + ',' + error.errMsg)
            })
            this.ad = null;
        }
    }
}